package framework.ui;

import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;

import org.openems.entity.Entity;
import org.openems.entity.Key;
import org.openems.entity.MarkerEntity;

import framework.DomainService;

public class EmsMarkerIcon extends EmsMarker {
	private TextField iconUrlTextField = new TextField();
	private String iconUrl;
	private Label icon;
	
	public EmsMarkerIcon(final Key markerKey, IChart chart, final DomainService service) {
		super(markerKey, chart, service);

        iconUrlTextField.setVisible(false);
        getChildren().add(iconUrlTextField);
        iconUrlTextField.setOnKeyPressed(new EventHandler<KeyEvent>() {
			@Override
			public void handle(KeyEvent arg0) {
				if (arg0.getCode() == KeyCode.ENTER) {
					iconUrlTextField.setVisible(false);
					MarkerEntity markerEntity = (MarkerEntity)service.getEntity(markerKey);
					markerEntity.setIconFile(iconUrlTextField.getText());
					service.putEntity(markerEntity);
				}
			}
        });
        
        this.setOnMouseClicked(new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent arg0) {
				if (arg0.getClickCount() == 2) {
					MarkerEntity markerEntity = (MarkerEntity)service.getEntity(markerKey);
					iconUrlTextField.setText(markerEntity.getIconFile());
					iconUrlTextField.setVisible(true);
				}
			}
        });
	}

	private boolean isIconChanged(Entity entity) {
		return !iconUrl.equals(((MarkerEntity)entity).getIconFile());
	}
	
	@Override
	protected void markerChanged(MarkerEntity entity) {
		if (isIconChanged(entity)) {
			iconUrl = entity.getIconFile();
			updateIcon(getIcon(), entity.getIconFile());
		}
	}

	private Label updateIcon(Label icon, String iconUrl) {
		this.iconUrl = iconUrl;
		Image image = new Image(iconUrl);
		double xofst = getBalloonWidth() / 2.0 - image.getWidth() / 2.0;
		double yofst = getBalloonHeight() / 2.0  - image.getHeight() / 2.0 - 10.0;
		icon.setLayoutX(xofst);
		icon.setLayoutY(yofst);
		icon.setGraphic(new ImageView(image));
		return icon;
	}

	@Override
	protected Node getContent(MarkerEntity markerEntity) {
		return updateIcon(getIcon(), markerEntity.getIconFile());
	}

	private Label getIcon() {
		if (icon == null) {
			icon = new Label();
		}
		return icon;
	}

}
